package com.shop.cereshop.business.utils;
import org.apache.commons.codec.binary.Base64;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JPushApiUtil {
    // 极光推送核心接口
    private static final String PUSH_URL = "https://api.jpush.cn/v3/push";
    // 替换为你的 AppKey 和 MasterSecret
    private static final String APP_KEY = "115628bf67fde2ff57a8f437";
    private static final String MASTER_SECRET = "dc2b4b32bad285591c03113d";

    /**
     * 发送推送消息
     * @param registrationId 目标设备的registrationId
     * @param title 通知标题
     * @param content 通知内容
     * @return 接口返回结果
     * @throws Exception 异常信息
     */
    public static String sendPush(String registrationId, String title, String content) throws Exception {
        // 1. 构建请求头（核心：Authorization 权限验证）
        String auth = APP_KEY + ":" + MASTER_SECRET;
        String base64Auth = Base64.encodeBase64String(auth.getBytes(StandardCharsets.UTF_8));
        String authorization = "Basic " + base64Auth;

        // 2. 构建请求体（JSON格式，严格遵循极光API规范）
        String requestBody = buildRequestBody(registrationId, title, content);

        // 3. 发送 HTTP POST 请求
        URL url = new URL(PUSH_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setRequestProperty("Authorization", authorization);

        // 4. 写入请求体
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 5. 读取响应结果
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            // 成功响应（可根据需求解析返回的JSON数据）
            return new String("成功");
        } else {

            throw new Exception("推送失败，响应码：" + responseCode + "，错误信息：" );
        }
    }

    /**
     * 构建请求体JSON
     */
    private static String buildRequestBody(String registrationId, String title, String content) {
        return String.format("{" +
                "\"platform\":\"all\"," + // 推送平台：all/android/ios
                "\"audience\":{\"registration_id\":[\"%s\"]}," + // 目标设备（单个或多个registrationId）
                "\"notification\":{" +
                "\"android\":{" +
                "\"alert\":\"%s\"," + // Android通知内容
                "\"title\":\"%s\"," + // Android通知标题
                "\"builder_id\":1" + // 自定义通知样式（可选）
                "}," +
                "\"ios\":{" +
                "\"alert\":\"%s\"," + // iOS通知内容
                "\"badge\":1," + // 角标+1
                "\"sound\":\"default\"" + // 通知声音（默认）
                "}" +
                "}," +
                "\"message\":{" + // 透传消息（可选，不显示在系统通知栏）
                "\"msg_content\":\"%s\"," +
                "\"content_type\":\"text\"" +
                "}," +
                "\"options\":{" +
                "\"time_to_live\":86400," + // 消息有效期（24小时）
                "\"apns_production\":false" + // 环境：false=开发环境，true=生产环境（iOS必填）
                "}" +
                "}", registrationId, content, title, content, content);
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            String registrationId = "13065ffa4f230a5ef79"; // 替换为实际设备的ID
            String result = sendPush(registrationId, "测试通知", "这是Java API调用极光推送的测试内容");
            System.out.println("推送成功，响应结果：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
